package com.gin.kotlin.no_gay_alliance.interceptor

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response

/**
 * 记录已经404的链接，不再执行该请求
 * @property notFoundUrl HashSet<String>
 */
class Block404Interceptor : Interceptor {
    private val notFoundUrl: HashSet<String> = HashSet()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val method = request.method
        val url = request.url.toString()
        if ("get".equals(method, ignoreCase = true) && notFoundUrl.contains(url)) {
            val message = "拦截404资源: $url"
            Log.d(this.javaClass.simpleName, message)
            return Response.Builder()
                .protocol(Protocol.HTTP_1_1)
                .message("Not Found")
                .request(request).code(404).build()
        }
        val res = chain.proceed(request)
        if (res.code == 404) {
            notFoundUrl.add(url)
        }
        return res
    }
}